

-- DROP FUNCTION scipg.array_to_relation(anyarray);

CREATE OR REPLACE FUNCTION scipg.array_to_relation(anyarray)
  RETURNS SETOF anyelement AS
$BODY$
DECLARE
    i int;
    n int;
BEGIN
    n := coalesce(array_upper($1, 1), 0);
    i := 1;

    LOOP
       IF i > n THEN
          EXIT;
       END IF;
       RETURN NEXT $1[i];
       i := i + 1;
    END LOOP;
    RETURN;
END
$BODY$
  LANGUAGE 'plpgsql' IMMUTABLE;
COMMENT ON FUNCTION scipg.array_to_relation(anyarray) IS 'Table function for iterating over array elements as a relation';


-- DROP AGGREGATE array_accum(anyelement);

CREATE AGGREGATE array_accum(
  BASETYPE=anyelement,
  SFUNC=array_append,
  STYPE=anyarray,
  INITCOND='{}'
);
COMMENT ON AGGREGATE scipg.array_accum(anyelement) IS 'Constructs an array from a group of field values';




CREATE OR REPLACE FUNCTION scipg.array_unique(anyarray)
  RETURNS anyarray AS
$BODY$
DECLARE
    i int;
    n int;
BEGIN
    n := coalesce(array_upper($1, 1), 0);
    i := 2;

    IF n < 1 THEN
      -- This never happens
      RETURN NULL;
    END IF;

    $0 = array_append($0,$1[1]);

    LOOP
       IF i > n THEN
          EXIT;
       END IF;
       IF not ($1[i] = ANY ($0)) THEN
         $0 = array_append($0,$1[i]);
       END IF;
       i := i + 1;
    END LOOP;
    RETURN $0;
END
$BODY$
  LANGUAGE 'plpgsql' IMMUTABLE;
COMMENT ON FUNCTION scipg.array_unique(anyarray) IS 'Create an array with the unique elments of the source array.  Order is stable.';
